// app.js
import {
  post,
  get
} from './utils/request'
import {
  APIS
} from './utils/api'
App({
  globalData: {
    userInfo: null,
    shareMessage: {
      title: '',
      imageUrl: '',
      path: "",
    }
  },
  onLaunch() {
    const that = this;
    wx.checkSession({
      success() {
        const token = wx.getStorageSync('token');
        const userInfo =  wx.getStorageSync('userInfo') || {};
        if (!token || !userInfo.id) {
          that.getLoginSession();
        }
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        that.getLoginSession();
      }
    });
  },
  onShow() {
    this.getUserInfo();
  },
  getLoginSession() {
    const that = this;
    wx.login({
      success(res) {
        const {
          code
        } = res;
        if (code) {
          wx.getUserInfo({
            success: function (res) {
              var userInfo = res.userInfo;
              that.setUserInfo(userInfo, code);
            }
          })
        }
      }
    })
  },
  getUserInfo() {
   const userInfo =  wx.getStorageSync('userInfo');
   if(userInfo.id) {
    get(`${APIS.user}/${userInfo.id}`).then(res => {
      try {
        const currentPage = getCurrentPages()[0].route;
        const info = res.data;
        wx.setStorageSync('userInfo', info);
        if(!info.phone && currentPage !== '/subPackage/pages/login') {
          wx.navigateTo({
            url: '/subPackage/pages/login'
          })
        }
      } catch (error) {
        
      }
    })
   }
  },
  setUserInfo(userInfo, code) {
    post(APIS.login, {
      code,
      ...userInfo
    }).then(result => {
      const {
        token,
        user
      } = result;
      wx.setStorageSync('token', token);
      wx.setStorageSync('userInfo', user);
      const pages = getCurrentPages();
      const perPage = pages[pages.length - 1];
      perPage.onShow();
    })
  }
})